﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using StockUtil;

namespace StockLib.UserData
{
    public class BlockCustomFileSaver
    {
        public virtual void Save()
        {
            StockBlockGroupCustom.Instance.GenerateZXGBlock();

            FileInfo fi = new FileInfo(StockUserData.Instance.GetFileName(UserDataType.Block));
            FileStream fs = null;
            StreamWriter sw = null;

            try
            {
                if (!fi.Directory.Exists)
                    Directory.CreateDirectory(fi.Directory.FullName);

                fs = new FileStream(fi.FullName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                sw = new StreamWriter(fs, Encoding.Default);

                foreach (StockBlock domain in StockBlockGroupCustom.Instance.Values)
                {
                    sw.WriteLine(domain.Name);
                    foreach (Stock stock in domain.Values)
                    {
                        sw.WriteLine(stock.CodeKey);
                    }
                    sw.WriteLine("-----");
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw ex;
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
    }
}